﻿using MeetingRoomBooking.Application.Common.Interfaces;
using MeetingRoomBooking.Domain.Entities;
using MeetingRoomBooking.Domain.Events;

namespace MeetingRoomBooking.Application.Rooms.Commands;
public class CreateRoomCommand:IRequest<int>
{
    public required string Name {  get; set; }
    public string? Description { get; set; }
    public int Capacity { get; set; }
}
public class CreateRoomCommandValidator : AbstractValidator<CreateRoomCommand>
{
    public CreateRoomCommandValidator()
    {
        RuleFor(x => x.Name).NotEmpty().WithMessage("Room name cannot be empty.");
        RuleFor(x => x.Capacity).GreaterThan(0).WithMessage("Capacity must be greater than 0.");
    }
}

public class CreateRoomCommandHander : IRequestHandler<CreateRoomCommand, int>
{
    private readonly IApplicationDbContext _context;  

    public CreateRoomCommandHander(IApplicationDbContext context)
    {
        _context = context;     
    }    

    public async Task<int> Handle(CreateRoomCommand request, CancellationToken cancellationToken)
    {
        Room room=new()
        { 
            Name=request.Name, 
            Description=request.Description,
            Capacity=request.Capacity,           
        };
        
        room.AddDomainEvent(new RoomCreatedEvent(room));

        _context.Rooms.Add(room);

        await _context.SaveChangesAsync(cancellationToken);
        
        return room.Id;
    }
}
